package com.geeka.d12.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class TcpServerDemo1 {
    public static void main(String[] args) {
        /**
         * 服务端
         */

        try (ServerSocket serverSocket = new ServerSocket(7777);
        ) {
            //阻塞等待别人连接, 有人连接才会继续执行
            // clientSocket 指向链接上来的客户端
            // clientSocket 指向连接上来的客户端
            System.out.println("服务端启动: "+ serverSocket.getLocalPort() );
            Socket clientSocket = serverSocket.accept();
            InputStream clientIps = clientSocket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(clientIps));
            String msg = null;
            // 不断等待对方的输入,然后打印到控制台
            while ((msg = br.readLine()) != null) {
                SocketAddress remoteSocketAddress = clientSocket.getRemoteSocketAddress();
                System.out.println(remoteSocketAddress + "对方说" + msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

